﻿using MediatR;
using MediatRApp.Command.Request;
using MediatRApp.IServices;
using MediatRApp.Models;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace MediatRApp.Command.Handler
{
    /// <summary>
    /// 创建用户命令处理程序
    /// </summary>
    public class CreateUserRequestHandler : IRequestHandler<CreateUserRequest, int>
    {
        private readonly IUserService userService;
        private readonly IMediator mediator;

        public CreateUserRequestHandler(IUserService userService, IMediator mediator)
        {
            this.userService = userService;
            this.mediator = mediator;
        }

        public async Task<int> Handle(CreateUserRequest request, CancellationToken cancellationToken)
        {
            // 创建用户
            UserInfo user = new UserInfo()
            {
                UserName = request.UserName,
                Email = request.Email
            };
            int userId = await userService.CreateUserAsync(user);

            // 发布用户创建事件
            await mediator.Publish(new UserCreatedEvent { UserId = userId, UserName = request.UserName });

            return userId;
        }
    }

    /// <summary>
    /// 获取单个用户查询处理程序
    /// </summary>
    public class GetUserQueryHandler : IRequestHandler<GetUserQuery, UserInfo>
    {
        private readonly IUserService userService;

        public GetUserQueryHandler(IUserService userService)
        {
            this.userService = userService;
        }

        public async Task<UserInfo> Handle(GetUserQuery request, CancellationToken cancellationToken)
        {
            return await userService.GetUserAsync(request.UserId);
        }
    }

    /// <summary>
    /// 获取所有用户查询处理程序
    /// </summary>
    public class GetAllUsersQueryHandler : IRequestHandler<GetAllUsersQuery, List<UserInfo>>
    {
        private readonly IUserService userService;

        public GetAllUsersQueryHandler(IUserService userService)
        {
            this.userService = userService;
        }

        public async Task<List<UserInfo>> Handle(GetAllUsersQuery request, CancellationToken cancellationToken)
        {
            return await userService.GetAllUsersAsync();
        }
    }

    /// <summary>
    /// 用户创建事件处理程序
    /// </summary>
    public class SendWelcomeEmailHandler : INotificationHandler<UserCreatedEvent>
    {
        public Task Handle(UserCreatedEvent notification, CancellationToken cancellationToken)
        {
            Console.WriteLine($"[邮件服务] 向用户 {notification.UserName} (ID: {notification.UserId}) 发送欢迎邮件");
            // 实际应用中这里会发送邮件
            return Task.CompletedTask;
        }
    }
}
